package com.f6;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.f6.common.util.SignUtil;
import com.f6.service.CoreService;

public class CoreServlet extends HttpServlet {
	
	/** 
     * 微信全网测试账号 
     */  
    private final static String COMPONENT_APPID = "wx35699088127e3724";
    private final static String COMPONENT_ENCODINGAESKEY = "GQk6hY6HejDEygh9XFLlno4ztgHDnFh0faZQKQJR9rG";  
    private final static String COMPONENT_TOKEN = "va9qq6";  

	/** 
     * 确认请求来自微信服务器 
     */    
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 微信加密签名  
        String signature = request.getParameter("signature");  
        // 时间戳  
        String timestamp = request.getParameter("timestamp");  
        // 随机数  
        String nonce = request.getParameter("nonce");  
        // 随机字符串  
        String echostr = request.getParameter("echostr");  
        
        String appid = request.getParameter("appId");
        if(appid != null && appid.startsWith("/")){
        	appid = appid.substring(1,appid.length());
        }
  
        System.out.println("doGet我是从get过来的哦..............^^^appid====^^^"+appid);
        PrintWriter out = response.getWriter();  
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (SignUtil.checkSignature(signature, timestamp, nonce,appid)) {  
            out.print(echostr);  
        }  
        out.close();  
        out = null;  
	}

	/** 
     * 处理微信服务器发来的消息 
     */  
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        String appid = request.getParameter("appId");
        System.out.println("doPost这里处理微信服务器发来的消息..^^^appid====^^^"+appid);
        if(appid != null && appid.contains("/")){
        	appid = appid.substring(1,appid.length());
        }
        
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");
        // 调用核心业务类接收消息、处理消息  
        String respMessage = CoreService.processRequest(request,appid);  
        // 响应消息  
        PrintWriter out = response.getWriter();  
        out.print(respMessage);  
        out.close();  
    } 
	
    
    /** 
     * 判断是否加密 
     * @param token 
     * @param signature 
     * @param timestamp 
     * @param nonce 
     * @return 
     */  
    public static boolean checkSignature(String token,String signature,String timestamp,String nonce){  
        System.out.println("checkSignature====###token:"+token+";signature:"+signature+";timestamp:"+timestamp+"nonce:"+nonce);  
           boolean flag = false;  
           if(signature!=null && !signature.equals("") && timestamp!=null && !timestamp.equals("") && nonce!=null && !nonce.equals("")){  
              String sha1 = "";  
              String[] ss = new String[] { token, timestamp, nonce };   
              Arrays.sort(ss);    
              for (String s : ss) {    
               sha1 += s;    
              }    
       
              sha1 = AddSHA1.SHA1(sha1);    
       
              if (sha1.equals(signature)){  
               flag = true;  
              }  
           }  
           return flag;  
       }
    
    /** 
     * 获取授权的Appid 
     * @param xml 
     * @return 
     */  
    String getAuthorizerAppidFromXml(String xml) {  
        Document doc;  
        try {  
            doc = DocumentHelper.parseText(xml);  
            Element rootElt = doc.getRootElement();  
            String toUserName = rootElt.elementText("ToUserName");  
            return toUserName;  
        } catch (DocumentException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return null;  
    }
    
    
  
 }

class AddSHA1 {  
    public static String SHA1(String inStr) {  
        MessageDigest md = null;  
        String outStr = null;  
        try {  
            md = MessageDigest.getInstance("SHA-1");     //选择SHA-1，也可以选择MD5  
            byte[] digest = md.digest(inStr.getBytes());       //返回的是byet[]，要转化为String存储比较方便  
            outStr = bytetoString(digest);  
        }  
        catch (NoSuchAlgorithmException nsae) {  
            nsae.printStackTrace();  
        }  
        return outStr;  
    }  
      
      
    public static String bytetoString(byte[] digest) {  
        String str = "";  
        String tempStr = "";  
          
        for (int i = 0; i < digest.length; i++) {  
            tempStr = (Integer.toHexString(digest[i] & 0xff));  
            if (tempStr.length() == 1) {  
                str = str + "0" + tempStr;  
            }  
            else {  
                str = str + tempStr;  
            }  
        }  
        return str.toLowerCase();  
    }  
}  
